package com.kunbo.shop.service.impl.history;

import static org.hamcrest.CoreMatchers.nullValue;

import java.io.File;
import java.io.FileOutputStream;
import java.io.StringWriter;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.kunbo.shop.dao.history.HistoryMotorDao;
import com.kunbo.shop.dao.history.HistoryOfferOrderDao;
import com.kunbo.shop.dao.history.HistoryPorductInfoDao;
import com.kunbo.shop.dao.history.HistoryProductDao;
import com.kunbo.shop.dao.history.HistoryProductParamsDao;
import com.kunbo.shop.entity.history.HistoryMotor;
import com.kunbo.shop.entity.history.HistoryOfferOrder;
import com.kunbo.shop.entity.history.HistoryPorductInfo;
import com.kunbo.shop.entity.history.HistoryProduct;
import com.kunbo.shop.entity.history.HistoryProductParams;
import com.kunbo.shop.entity.sort.ProductSort;
import com.kunbo.shop.service.history.HistoryProductService;
import com.kunbo.shop.service.sort.ProductSortService;
import com.shuohe.service.util.sql.EasyuiServiceImpl;
import com.shuohe.util.date.SDate;
import com.shuohe.util.db.DbQuerySql;
import com.shuohe.util.easyuiBean.EasyUiDataGrid;
import com.shuohe.util.returnBean.ReturnBean;
import com.shuohe.util.returnBean.ReturnBean3;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

@Service
public class HistoryProductServiceImpl implements HistoryProductService {

	@Autowired
	HistoryPorductInfoDao historyPorductInfoDao;
	@Autowired
	HistoryOfferOrderDao historyOfferOrderDao;

	@Autowired
	HistoryMotorDao historyMotorDao;

	@Autowired
	HistoryProductParamsDao historyProductParamsDao;

	@Autowired
	HistoryProductDao historyProductDao;

	// @Autowired EasyUiDTO easyUiDTO;

	@Autowired
	EasyuiServiceImpl easyuiServiceImpl;

	@Autowired
	ProductSortService productSortService;
	
	@Value("${myPath.xmlPath}")
	private String xmlPath;

	@Override
	public List<HistoryPorductInfo> converJsonToHistoryPorductInfo(String json) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public ReturnBean saveHistoryPorductOfferOrder(String data, String orderId,
			String motor, String params, String productLineId,
			String productJson, String productId, String materialId,
			double totalPrice, double unitPrice, int num, double fanProfitRate,
			double motorProfitRate, double offerUnitPrice,
			double offerTotalPrice) {
		// TODO Auto-generated method stub
		Gson reGson = new Gson();
		// 保存产品
		HistoryProduct historyProduct = new HistoryProduct();
		historyProduct.setChanged(false); // 默认没有改变过部件的价格
		historyProduct.setMaterialId(materialId); //
		// historyProduct.setMotorId(MotorId);
		historyProduct.setNum(num);
		historyProduct.setOrderId(orderId);
		historyProduct.setProductJson(productJson);
		historyProduct.setProductLineId(productLineId);
		// 混合产生一个产品编号
		ProductSort nowProductSort = productSortService.findById(productId);
		ProductSort parentProductSort = productSortService
				.getParentById(productId);
		historyProduct.setProductNumber(parentProductSort.getText()
				+ nowProductSort.getProductNumber());
		historyProduct.setQuoteDate(SDate.getSystemDate());
		historyProduct.setTotalPrice(totalPrice);
		historyProduct.setUnitPrice(unitPrice);
		historyProduct.setFanProfitRate(fanProfitRate);
		historyProduct.setMotorProfitRate(motorProfitRate);
		historyProduct.setOfferUnitPrice(offerUnitPrice);
		historyProduct.setOfferTotalPrice(offerTotalPrice);
		historyProductDao.save(historyProduct);

		// 保存产品结构表
		String _data = data.replaceAll("\"\"", "null");
		List<HistoryPorductInfo> historyPorductInfo_list = reGson.fromJson(
				_data, new TypeToken<List<HistoryPorductInfo>>() {
				}.getType());
		List<HistoryPorductInfo> HistoryPorductInfoSaveList = new LinkedList<HistoryPorductInfo>();
		for (HistoryPorductInfo h : historyPorductInfo_list) {
			h.setOrderId(orderId);
			h.setHistorypProductId(historyProduct.getId());
			HistoryPorductInfoSaveList.add(h);
		}
		historyPorductInfoDao.save(HistoryPorductInfoSaveList);

		// 保存电机
		String _motor = motor.replaceAll("\"\"", "null");
		System.out.println("_motor = " + _motor);
		HistoryMotor historyMotor = reGson.fromJson(_motor,
				new TypeToken<HistoryMotor>() {
				}.getType());
		historyMotor.setOrderId(orderId);
		historyMotor.setHistorypProductId(historyProduct.getId());
		historyMotorDao.save(historyMotor);

		// 保存参数
		String _params = params.replaceAll("\"\"", "null");
		List<HistoryProductParams> historyProductParams = reGson.fromJson(
				_params, new TypeToken<List<HistoryProductParams>>() {
				}.getType());
		List<HistoryProductParams> HistoryProductParamsList = new LinkedList<HistoryProductParams>();
		for (HistoryProductParams h : historyProductParams) {
			h.setOrderId(orderId);
			h.setHistorypProductId(historyProduct.getId());
			HistoryProductParamsList.add(h);
		}
		historyProductParamsDao.save(HistoryProductParamsList);

		refreshHistoryOrder(orderId);

		return new ReturnBean(true, "保存报价单");

	}

	/**
	 * @Description: 刷新订单，包括重新计算订单成本总价、报价总价、数量、最后修改时间等
	 * @Title: refreshHistoryOrder
	 * @param orderId
	 * @return boolean
	 * @author qin
	 * @date 2019年1月5日上午12:47:30
	 */
	boolean refreshHistoryOrder(String orderId) {
		// 1、根据订单号获得订单实例
		HistoryOfferOrder hoo = historyOfferOrderDao.findById(orderId);
		// 2、从数据库内获得所有本订单的产品订单详情
		List<HistoryProduct> l = historyProductDao.findByOrderId(orderId);
		// 3、重新计算订单总产品数量、订单成本总价、报价总价

		int productCount = 0; // 产品数量
		int productTypeCount = 0; // 产品种类
		double offerTotalPrice = 0;// 报价总价
		double totalPrice = 0;// 成本总价
		for (HistoryProduct h : l) {
			// 废弃的单据不计入总价中
			if (!h.isDiscard()) {
				productCount += h.getNum();
				offerTotalPrice += h.getOfferTotalPrice();
				totalPrice += h.getTotalPrice();
			}
		}
		hoo.setProductCount(productCount);
		hoo.setOfferTotalPrice(offerTotalPrice);
		hoo.setTotalPrice(totalPrice);
		hoo.setQuoteLastModifyDate(SDate.getSystemDate());
		historyOfferOrderDao.save(hoo);
		return true;
	}

	public List<HistoryPorductInfo> getChildsManyGroup(
			List<HistoryPorductInfo> list, String pid) {
		List<HistoryPorductInfo> arr = new ArrayList<HistoryPorductInfo>();
		for (HistoryPorductInfo location : list) {
			if (pid.equals(location.getPid())) {
				location.setChildren(getChildsManyGroup(list,
						location.getTemplateInfoId()));
				arr.add(location);
			}
		}
		return arr;
	}

	@Override
	public List<HistoryPorductInfo> getHistoryProductInfoByProductOfferId(
			String offerProuctId) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<HistoryOfferOrder> getOrderByUser(int userId) {
		return historyOfferOrderDao.findByQuotePeopleId(userId + "");
	}

	@Override
	public ReturnBean3 saveOrder(HistoryOfferOrder historyOfferOrder) {
		HistoryOfferOrder r = historyOfferOrderDao.save(historyOfferOrder);
		return new ReturnBean3(true, r);
	}

	@Override
	public ReturnBean deleteOrderById(String id) {
		int ret = historyOfferOrderDao.deleteById(id);
		return new ReturnBean(true, ret + "");
	}

	@Override
	public EasyUiDataGrid getOrderByUserPage(String userId,
			String customerName, String text, String page, String row) {
		// TODO Auto-generated method stub
		System.out.println("userId = " + userId);
		String sql = "";
		sql += " SELECT";
		sql += " 	*";
		sql += " FROM";
		sql += " 	db_offer_history_offer";
		sql += " WHERE 1=1 ";
		if(StringUtils.isNotBlank(userId)){
			sql += " and	db_offer_history_offer.quotePeopleId = '" + userId + "'";
		}
		if(StringUtils.isNotBlank(customerName)){
			sql += " and	db_offer_history_offer.customerName like '%" + customerName + "%'";
		}
		if(StringUtils.isNotBlank(text)){
			sql += " and	db_offer_history_offer.text  like '%" + text + "%'";
		}
		sql += " order by quoteDate desc";
		sql += DbQuerySql.limit(page, row);

		String count_sql = "";
		count_sql += " SELECT";
		count_sql += " 	count(*)";
		count_sql += " FROM";
		count_sql += " 	db_offer_history_offer";
		count_sql += " WHERE 1=1 ";
		if(StringUtils.isNotBlank(userId)){
			count_sql += " and	db_offer_history_offer.quotePeopleId = '" + userId + "'";
		}
		if(StringUtils.isNotBlank(customerName)){
			count_sql += " and	db_offer_history_offer.customerName like '%" + customerName + "%'";
		}
		if(StringUtils.isNotBlank(text)){
			count_sql += " and	db_offer_history_offer.text  like '%" + text + "%'";
		}
		//count_sql += " 	db_offer_history_offer.quotePeopleId = '" + userId	+ "'";
		return easyuiServiceImpl.getEasyUiDataGrid(sql, count_sql);
	}

	@Override
	public HistoryProduct getHistoryProductById(String id) {
		// TODO Auto-generated method stub
		HistoryProduct hp = historyProductDao.findById(id);
		hp.setParams(historyProductParamsDao.findByHistorypProductId(id));
		hp.setMotor(historyMotorDao.findByHistorypProductId(id));
		hp.setInfos(historyPorductInfoDao.findByHistorypProductId(id));
		return hp;
	}

	@Override
	public HistoryOfferOrder getOrderById(String id) {
		return historyOfferOrderDao.findById(id);
	}

	@Override
	public List<HistoryProduct> getHistoryProductByOrderId(String orderId) {
		return historyProductDao.findByOrderId(orderId);
	}

	@Override
	public ReturnBean discardProductById(String id, boolean isDiscard) {
		historyProductDao.updateToDiscard(id, isDiscard);
		HistoryProduct historyProduct = historyProductDao.findById(id);
		refreshHistoryOrder(historyProduct.getOrderId());		
		//删除报价子项
		historyProductDao.deleteById(id);
		return new ReturnBean(true, "");
	}

	@Override
	public ReturnBean exportXML(String id) {
		HistoryOfferOrder order = historyOfferOrderDao.findById(id);
		if(order == null){
			return new ReturnBean(false, "该订单为空");
		}
		// 创建XML
		Document doc = DocumentHelper.createDocument();
		doc.setXMLEncoding("UTF-8");
		DecimalFormat df = new DecimalFormat("#0.00");
		/*<th field="text">报价单号</th>                
        <th field="quotePeopleName">填录人</th>
        <th field="customerName">客户名称</th>
        <!-- <th field="productTypeCount">种类</th>   -->
        <th field="productCount">数量</th>  
        <th field="totalPrice" formatter='Easyui.Datagraid.formatterDecimal2'>成本总价</th>  
        <th field="offerTotalPrice" formatter='Easyui.Datagraid.formatterDecimal2'>报价总价</th>                      
        <th field="quoteDate">报价单创建时间</th>*/
		Element userdata = doc.addElement("userdata");
		userdata.addAttribute("createuser", "false");
		Element dataconnection = userdata.addElement("dataconnection");
		Element account = dataconnection.addElement("account");
		account.setText(order.getQuotePeopleAccount());
		Element name = dataconnection.addElement("name");
		name.setText(order.getQuotePeopleName());
		Element PU_Plan_M = userdata.addElement("PU_Plan_M");
		Element text = PU_Plan_M.addElement("text");
		text.setText(order.getText());
		Element quotePeopleName = PU_Plan_M.addElement("quotePeopleName");
		quotePeopleName.setText(order.getQuotePeopleName());
		Element customerName = PU_Plan_M.addElement("customerName");
		customerName.setText(order.getCustomerName());
		Element productCount = PU_Plan_M.addElement("productCount");
		productCount.setText(String.valueOf(order.getProductCount()));
		Element totalPrice = PU_Plan_M.addElement("totalPrice");
		totalPrice.setText(String.valueOf(df.format(order.getTotalPrice())));
		Element offerTotalPrice = PU_Plan_M.addElement("offerTotalPrice");
		offerTotalPrice.setText(String.valueOf(df.format(order.getOfferTotalPrice())));
		Element quoteDate = PU_Plan_M.addElement("quoteDate");
		quoteDate.setText(SDate.praseYMDHMSDate(order.getQuoteDate()));
		Element curDate = PU_Plan_M.addElement("curDate");
		curDate.setText(SDate.getSystemDateYMDToString());//getSystemDateYMDToString
		
		
		/*typeEl.addAttribute("text",  order.getText());
		typeEl.addAttribute("quotePeopleName",  order.getQuotePeopleName());
		typeEl.addAttribute("customerName",  order.getCustomerName());
		typeEl.addAttribute("productCount",  String.valueOf(order.getProductCount()));
		typeEl.addAttribute("totalPrice",  String.valueOf(df.format(order.getTotalPrice())));
		typeEl.addAttribute("offerTotalPrice", String.valueOf(df.format(order.getOfferTotalPrice())));
		typeEl.addAttribute("quoteDate", SDate.praseYMDHMSDate(order.getQuoteDate()));*/
		
		List<HistoryProduct> childList = this.historyProductDao.findByOrderId(id);
		if(childList != null && childList.size() > 0){
			
			for (HistoryProduct entity : childList) {
				 /*<th field="id" hidden>uuid</th>                
                 <th field="productNumber">风机型号</th>                
                 <th field="fanProfitRate">风机利润率</th>  
                 <th field="motorProfitRate">电机利润率</th>        
                 <th field="unitPrice" formatter='Easyui.Datagraid.formatterDecimal2'>成本单价</th>                
                 <th field="offerUnitPrice" formatter='Easyui.Datagraid.formatterDecimal2'>报价单价</th>
                 <th field="num">数量</th>
                 <th field="totalPrice" formatter='Easyui.Datagraid.formatterDecimal2'>成本总价</th>  
                 <th field="offerTotalPrice" formatter='Easyui.Datagraid.formatterDecimal2'>报价总价</th>  
                 <th field="quoteDate">报价时间</th>   */
				Element PU_Plan_T = userdata.addElement("PU_Plan_T");
				Element url = PU_Plan_T.addElement("url");
				url.setText("http://27.221.114.67:9009/pages/offer/quote/viewOffer.jsp?id="+entity.getId());
				Element productNumber = PU_Plan_T.addElement("productNumber");
				productNumber.setText(entity.getProductNumber());
				Element fanProfitRate = PU_Plan_T.addElement("fanProfitRate");
				fanProfitRate.setText(String.valueOf(df.format(entity.getFanProfitRate())));
				Element motorProfitRate = PU_Plan_T.addElement("motorProfitRate");
				motorProfitRate.setText(String.valueOf(df.format(entity.getMotorProfitRate())));
				Element unitPrice = PU_Plan_T.addElement("unitPrice");
				unitPrice.setText(String.valueOf(df.format(entity.getUnitPrice())));
				Element offerUnitPrice = PU_Plan_T.addElement("offerUnitPrice");
				offerUnitPrice.setText(String.valueOf(df.format(entity.getOfferUnitPrice())));
				Element num = PU_Plan_T.addElement("num");
				num.setText(String.valueOf(entity.getNum()));
				Element totalPrice1 = PU_Plan_T.addElement("totalPrice");
				totalPrice1.setText(String.valueOf(df.format(entity.getTotalPrice())));
				Element offerTotalPrice1 = PU_Plan_T.addElement("offerTotalPrice");
				offerTotalPrice1.setText(String.valueOf(df.format(entity.getOfferTotalPrice())));
				Element quoteDate1 = PU_Plan_T.addElement("quoteDate");
				quoteDate1.setText(SDate.praseYMDHMSDate(entity.getQuoteDate()));
				
				/*Element child = typeEl.addElement("childOffer");
				child.addAttribute("url",  "http://27.221.114.67:9009/pages/offer/quote/viewOffer.jsp?id="+entity.getId());
				child.addAttribute("productNumber",  entity.getProductNumber());
				child.addAttribute("fanProfitRate",  String.valueOf(df.format(entity.getFanProfitRate())));
				child.addAttribute("motorProfitRate",  String.valueOf(df.format(entity.getMotorProfitRate())));
				child.addAttribute("unitPrice",  String.valueOf(df.format(entity.getUnitPrice())));
				child.addAttribute("offerUnitPrice",  String.valueOf(df.format(entity.getOfferUnitPrice())));
				child.addAttribute("num",  String.valueOf(entity.getNum()));
				child.addAttribute("totalPrice",  String.valueOf(df.format(entity.getTotalPrice())));
				child.addAttribute("offerTotalPrice",  String.valueOf(df.format(entity.getOfferTotalPrice())));
				child.addAttribute("quoteDate",  SDate.praseYMDHMSDate(entity.getQuoteDate()));*/
			}
		}
		//输出格式化XML
		try {
			OutputFormat format = OutputFormat.createPrettyPrint();
			// 设置编码格式
			format.setEncoding("UTF-8");
			File file = new File(xmlPath+System.currentTimeMillis()+".xml");
			XMLWriter writer = new XMLWriter(new FileOutputStream(file), format);
			writer.write(doc);
			writer.close();
			return new ReturnBean(true, "");
		} catch (Exception e) {
			e.printStackTrace();
			return new ReturnBean(false, e.toString());
		}
	}
}
